extends Panel

signal panel_closed
signal item_purchased(item_id: String, count: int)
signal item_sold(item_id: String, count: int)

var economy: Economy

func _ready():
	visible = false

func show_panel(econ: Economy):
	economy = econ
	update_display()
	visible = true

func hide_panel():
	visible = false
	panel_closed.emit()

func update_display():
	if not economy:
		return
	
	update_buy_list()
	update_sell_list()

func update_buy_list():
	var buy_list = $VBoxContainer/TabContainer/购买/BuyList
	
	# 清除现有项目
	for child in buy_list.get_children():
		child.queue_free()
	
	# 添加可购买物品
	var shop_items = economy.get_shop_items()
	
	for item in shop_items:
		var item_container = HBoxContainer.new()
		
		var name_label = Label.new()
		name_label.text = item.name
		name_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		
		var price_label = Label.new()
		price_label.text = "%d金币" % item.price
		
		var buy_button = Button.new()
		buy_button.text = "购买"
		buy_button.pressed.connect(_on_buy_item.bind(item.id, 1))
		
		# 检查是否买得起
		if not economy.can_afford(item.id, 1):
			buy_button.disabled = true
			buy_button.text = "金币不足"
		
		item_container.add_child(name_label)
		item_container.add_child(price_label)
		item_container.add_child(buy_button)
		buy_list.add_child(item_container)

func update_sell_list():
	var sell_list = $VBoxContainer/TabContainer/出售/SellList
	
	# 清除现有项目
	for child in sell_list.get_children():
		child.queue_free()
	
	# 添加可出售物品
	var sellable_items = economy.get_sellable_items()
	
	if sellable_items.size() == 0:
		var empty_label = Label.new()
		empty_label.text = "没有可出售的作物"
		empty_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		sell_list.add_child(empty_label)
		return
	
	for item in sellable_items:
		var item_container = HBoxContainer.new()
		
		var name_label = Label.new()
		name_label.text = "%s x%d" % [item.name, item.count]
		name_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		
		var price_label = Label.new()
		price_label.text = "总价: %d金币" % item.total_value
		
		var sell_button = Button.new()
		sell_button.text = "全部出售"
		sell_button.pressed.connect(_on_sell_item.bind(item.id, item.count))
		
		item_container.add_child(name_label)
		item_container.add_child(price_label)
		item_container.add_child(sell_button)
		sell_list.add_child(item_container)

func _on_buy_item(item_id: String, count: int):
	if economy.buy_item(item_id, count):
		item_purchased.emit(item_id, count)
		update_display()  # 刷新显示

func _on_sell_item(item_id: String, count: int):
	if economy.sell_item(item_id, count):
		item_sold.emit(item_id, count)
		update_display()  # 刷新显示

func _on_close_button_pressed():
	hide_panel()